/**
 * 配置浏览器本地存储的方式，可直接存储对象数组。
 */
import { json } from '@/utils'
export const nameSpace = 'CK'
export enum CACHE_KEY {
  // ---------- 系统
  // 全局配置
  SYSTEM_CONFIG = nameSpace + '_SYSTEM_CONFIG',
  // token 等信息
  SYSTEM_ACCESS_TOKEN = nameSpace + '_ACCESS_TOKEN',
  // 刷新 token 等信息
  SYSTEM_REFRESH_TOKEN = nameSpace + '_REFRESH_TOKEN',
  // 用户信息
  SYSTEM_USER_INFO = nameSpace + '_USER_INFO',
  // 固定的标签栏
  SYSTEM_FIXED_TAG = nameSpace + '_FIXED_TAG',
  // 全部标签栏
  SYSTEM_ALL_TAG = nameSpace + '_ALL_TAG',
  // 语种
  SYSTEM_LOCALE = nameSpace + '_LOCALE',
  // 字典
  SYSTEM_DICT = nameSpace + '_DICT',
  // 角色权限
  SYSTEM_ROLE_PERMIT = nameSpace + '_ROLE_PERMIT',

  // ---------- 登录
  // 登录模板
  LOGIN_TEMPLATE = nameSpace + '_LOGIN_TEMPLATE',
  // 登录表单
  LOGIN_FORM = nameSpace + '_LOGIN_FORM',
  // 租户ID
  LOGIN_TENANT_ID = nameSpace + '_LOGIN_TENANT_ID',
  // 登录验证码倒计时
  LOGIN_SIGN_COUNTDOWN = nameSpace + '_SIGN_COUNTDOWN',
  // 找回密码验证码倒计时
  LOGIN_RECOVER_COUNTDOWN = nameSpace + '_RECOVER_COUNTDOWN',
  // 注册验证码倒计时
  LOGIN_REGISTER_COUNTDOWN = nameSpace + '_REGISTER_COUNTDOWN',
  // 登录页面的插画类型
  LOGIN_ILLUSTRATIONS_TYPE = nameSpace + '_ILLUSTRATIONS_TYPE'
}
interface ProxyStorage {
  getItem(key: string): any
  setItem(Key: string, value: string): void
  removeItem(key: string): void
  clear(): void
}

// sessionStorage operate
class SessionStorageProxy implements ProxyStorage {
  protected storage: ProxyStorage

  constructor(storageModel: ProxyStorage) {
    this.storage = storageModel
  }

  // 存
  public setItem(key: string, value: any): void {
    this.storage.setItem(key, json.stringify(value))
  }

  // 取
  public getItem(key: string): any {
    return json.parse(this.storage.getItem(key))
  }

  // 删
  public removeItem(key: string): void {
    this.storage.removeItem(key)
  }

  // 清空
  public clear(): void {
    this.storage.clear()
  }
}

// localStorage operate
class LocalStorageProxy extends SessionStorageProxy implements ProxyStorage {
  constructor(localStorage: ProxyStorage) {
    super(localStorage)
  }
}

export const useCache = () => {
  const wsSession = new SessionStorageProxy(sessionStorage)

  const wsLocal = new LocalStorageProxy(localStorage)

  return {
    wsSession,
    wsLocal
  }
}
